#include "mem_pool.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// void inno_log_error(const char* cmd_fmt, ...) {
// }
// void inno_log_info(const char* cmd_fmt, ...) {
// }

/* Initialize the memory pool */
void mem_pool_init(InnoMemPool* m_pool) {
  void* tmp_ptr = m_pool->mem_pool;
  m_pool->free_block_list = (InnoMemBlock*)tmp_ptr;
  InnoMemBlock* current_block = m_pool->free_block_list;

  /* Initialize the free list */
  size_t num_blocks = INNO_MEM_POOL_SIZE / INNO_MEM_BLOCK_SIZE - 1;
  for (size_t i = 0; i < num_blocks; ++i) {
    void* next_block_ptr = (void*)current_block + INNO_MEM_BLOCK_SIZE;
    current_block->next_block = (InnoMemBlock*)next_block_ptr;
    current_block = current_block->next_block;
  }
  current_block->next_block = NULL;
}

/* Allocate memory from the memory pool */
uint8_t* mem_pool_alloc(InnoMemPool* m_pool) {
  uint8_t* allocated_block = NULL;

  if (m_pool->free_block_list != NULL) {
    allocated_block = (uint8_t*)m_pool->free_block_list;
    m_pool->free_block_list = m_pool->free_block_list->next_block;
  }

  return allocated_block;
}

// static InnoMemBlock freed_block_aa1;
// static InnoMemBlock* freed_block = &freed_block_aa1;

/* Free memory to the memory pool */
void mem_pool_free(InnoMemPool* m_pool, uint8_t* free_ptr) {
  InnoMemBlock* freed_block = NULL;
  if (free_ptr != NULL) {
    // Copy the content of the memory block to freed_block using memcpy
    void* tmp_ptr = (void*)free_ptr;
    freed_block = (InnoMemBlock*)tmp_ptr;

    // Perform the necessary operations on freed_block
    freed_block->next_block = m_pool->free_block_list;
    m_pool->free_block_list = freed_block;
  }
}
